package com.block.channel.flow.channel;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.channel.enums.ReportChannelEnum;
import com.block.channel.flow.IChannelReportService;
import com.block.channel.model.result.ReprotFlowResult;
import com.block.common.bean.CommonParam;
import com.block.common.service.LogFactory;
import com.block.db.entity.ChannelBaseInfo;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.mapper.MemberSourceInfoMapper;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;


/**
 * http://ocpc.baidu.com/ocpcapi/cb/actionCb?a_type=activate&a_value=0&s=123&ext_info={}
 */
@Service
public class BaiDuH5ChannelReportService implements IChannelReportService {

    private static Logger log = LogFactory.getCommLog();

    public static String REQUEST_URL = "https://ocpc.baidu.com/ocpcapi/api/uploadConvertData";

    public static Map<String, String> TOKEN_MAP = new HashMap<>();
    static {
        TOKEN_MAP.put(ReportChannelEnum.BAIDU002.getValue(), "Yg6JWuabxOU6GlgPnEczAXegqbWfHD9n@1SkCingvWHoIqRiDqprB7NrFNujWMBP6");
        TOKEN_MAP.put("11", "Yg6JWuabxOU6GlgPnEczAXegqbWfHD9n@1SkCingvWHoIqRiDqprB7NrFNujWMBP6");

        TOKEN_MAP.put(ReportChannelEnum.BAIDU003.getValue(), "e66uw3fVSMmFkPfrWWO7OZUTihZsjP6r@bAa9ZzSRTXKKFLKMD2Zt6IwqHT4eeol6");
        TOKEN_MAP.put("12", "e66uw3fVSMmFkPfrWWO7OZUTihZsjP6r@bAa9ZzSRTXKKFLKMD2Zt6IwqHT4eeol6");

        TOKEN_MAP.put(ReportChannelEnum.BAIDU004.getValue(), "UCO6AL1RKWecSflsd0zKJPeoaqPhshKc@XLt5d0BUHSVbMTfwXt5HN0RLSOG9KPgW");
        TOKEN_MAP.put("13", "UCO6AL1RKWecSflsd0zKJPeoaqPhshKc@XLt5d0BUHSVbMTfwXt5HN0RLSOG9KPgW");

        TOKEN_MAP.put(ReportChannelEnum.BAIDU005.getValue(), "fF2HnbQdE9JSblPGmIPdKsiHdjGqDdzt@JeXLEkflEZSic2GQbcKjr5OZ4f6WHcqn");
        TOKEN_MAP.put("14", "fF2HnbQdE9JSblPGmIPdKsiHdjGqDdzt@JeXLEkflEZSic2GQbcKjr5OZ4f6WHcqn");

        TOKEN_MAP.put(ReportChannelEnum.BAIDU006.getValue(), "pk13LEXgF2BKeqn0ON1y1E9VjZ1Ze21w@Z709eUmbJn5slJQjTzOBlA9KJLVzfeME");
        TOKEN_MAP.put("15", "pk13LEXgF2BKeqn0ON1y1E9VjZ1Ze21w@Z709eUmbJn5slJQjTzOBlA9KJLVzfeME");
    }

    @Resource
    MemberSourceInfoMapper memberSourceInfoMapper;

    @Override
    public ReprotFlowResult registerActionReport(CommonParam commonParam, ChannelBaseInfo channelBaseInfo) {
        throw new RuntimeException("");
    }

    @Override
    public ReprotFlowResult sourceActionReport(CommonParam commonParam, ChannelBaseInfo channelBaseInfo) {

        ReprotFlowResult flowResult = new ReprotFlowResult();
        flowResult.setSuccess(false);

        JSONObject headObject = commonParam.getHeadObject();

        String bdvid = headObject.getString("bdvid");
        String accountid = headObject.getString("accountid");

        // 返回失败的时候，把请求头信息存储下来
        flowResult.setParamInfo(JSON.toJSONString(headObject));
        if (StrUtil.isEmpty(bdvid)) {
            flowResult.setCode("-2");
            flowResult.setMessage("bdvid参数为空，不做处理");
            return flowResult;
        }

        MemberSourceInfo memberSourceInfo = memberSourceInfoMapper.selectById(commonParam.getUid());
        if (ObjectUtil.isEmpty(memberSourceInfo)){
            flowResult.setCode("-4");
            flowResult.setMessage("用户信息为空");
            return flowResult;
        }
        Integer age = memberSourceInfo.getAge();
        if (age < 23 || age > 45){
            flowResult.setCode("-5");
            flowResult.setMessage("年龄不符合：" + age);
            return flowResult;
        }

        String channelCode = channelBaseInfo.getChannelCode();
//        String token = TOKEN_MAP.get(channelCode);
        String token = TOKEN_MAP.get(accountid);

        String reqUrl = REQUEST_URL;

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("token", token);

        JSONArray conversionTypes = new JSONArray();

        String logIdUrl = StrUtil.format("{}?bd_vid={}", channelBaseInfo.getPageUrl(), bdvid);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("logidUrl", logIdUrl);
        jsonObject.put("newType", "3");
        conversionTypes.add(jsonObject);

        paramMap.put("conversionTypes", conversionTypes);

        log.info("【百度h5信息流上报】【注册】【开始请求】【reqestUrl】{}", reqUrl);
        String response = HttpUtil.createPost(reqUrl)
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【百度h5信息流上报】【注册】【开始结束】【result】{}", response);

        JSONObject resultObject = JSONObject.parseObject(response);
        JSONObject header = resultObject.getJSONObject("header");
        Integer status = header.getInteger("status");
        String desc = header.getString("desc");

        flowResult.setCode(String.valueOf(status));
        flowResult.setMessage(desc);
        flowResult.setParamInfo(reqUrl);
        flowResult.setResultInfo(response);
        if (ObjectUtil.equals(status, Integer.valueOf("0"))){
            flowResult.setSuccess(true);
        }else{
            flowResult.setSuccess(false);
        }
        return flowResult;
    }

    @Override
    public ReprotFlowResult downloadActionReport(CommonParam commonParam, ChannelBaseInfo channelBaseInfo) {
        return null;
    }

    @Override
    public ReprotFlowResult payBuyActionReport(CommonParam commonParam, ChannelBaseInfo channelBaseInfo) {
        return null;
    }

}
